package com.ruihang.generalibrary.ui.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.R;
import com.ruihang.ijkplaylib.listener.OnStatusChanged;
import com.ruihang.ijkplaylib.widget.GPlayerView;
import com.ruihang.ijkplaylib.bean.IPlayClarity;
import com.ruihang.ijkplaylib.widget.IGPlayerConstructorCallback;
import com.ruihang.ijkplaylib.widget.PlayStateParams;

import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by panxd on 2016/9/14.
 */
public class FloatVideoUtils implements IMediaPlayer.OnBufferingUpdateListener
        , IMediaPlayer.OnInfoListener, OnStatusChanged {

    private Context context;

    private Activity activity;

    private View parentView;//用以确定playerview位置的view（竖屏时)
    private View mediaView;

    private AbsoluteLayout.LayoutParams flParam;
    private AbsoluteLayout.LayoutParams tempParam;
    private AbsoluteLayout videoLayout;

    private ImageView ivDefaultPic;
    private ProgressBar pb;

//    private WoPlayerView.IPlayingTimeListener playingTimeListener;

    private Uri uri;

    private long currentPostion;

    private int statusHeight;

    private int parentWidth, parentHeight, parentX, parentY;

    private String currentPath;

    private boolean isStop = false;

    private boolean isAboutStatusHeiht = true;

    private GPlayerView playerView;

    private boolean isBackValued;

    private View backView;

    private int backViewColor;

    private int otherHeight;
    /**
     * 竖屏时，parentview所在viewgroup的Y偏移量
     */
    private int scrolledY;
    /**
     * 如果为true，则播放区域不能滑出屏幕或超出屏幕外
     */
    private boolean isShowFull;

    private boolean isPlayerAutoPlay;//播放器是否自动隐藏控制条

    private IMediaPlayer.OnSeekCompleteListener seekCompleteListener;

    private boolean isAutoPlayNext;//是否自动播放

    private IAutoPlayAction autoPlay;//自动播放的接口

    private IMediaPlayer.OnInfoListener onInfoListener;

    private OnStatusChanged onStatusChanged;

//    private GPlayerView.IPanlShowingListener panlShowingListener;
//
//    private WoPlayerView.IFullScreenClick fullScreenClick;

    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    private List<IPlayClarity> claritiesTemp;//清晰度缓存

    private boolean shouldSetClaryty;

    private View.OnClickListener playerMenuClick;
    private View.OnClickListener playerNextClick;

    private boolean isLogin;

    private int topMode;
    /**
     * 是否只在顶部显示
     */
    private boolean isTop;

    private Handler handler;
    /**
     * 是否是直播
     */
    private boolean isLiving;

    private boolean isPortrait = true;//是否是竖屏

    public static final int TOPMODE_DEF = 0;
    public static final int TOPMODE_LIVING = 1;
    public static final int TOPMODE_DEMAND = 2;

//    private SpeedSdkHelper speedSdkHelper;

    public interface OnPlayingListener {
        void onChangedToPlaying();

        void onChangeToUnPlaying();

        void onChangedToStop();

        boolean isStoped();
    }

    private OnPlayingListener onPlayingListener;

    private ScrollTemp scrollTemp = new ScrollTemp();//用于滑动缓存等

    private IGPlayerConstructorCallback constructorCallback;

    private RecyclerView.OnScrollListener recyclerScrollListener = new RecyclerView.OnScrollListener() {

        private int stateTemp;

        private boolean tempDown;//注意：手指往上滑动是自动向下播放

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            stateTemp = newState;
//            JLog.e("scroll state:" + newState);
//            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                if (isAutoPlayNext && mediaView.getVisibility()==View.GONE && autoPlay != null) {
//                    autoPlay.autoNext(parentView,tempDown);
//                }
//            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
//            JLog.e("dy:" + dy + "  py:" + parentView.getY() + " pt :" + parentView.getTop());
            if (mediaView != null && mediaView.getVisibility() == View.VISIBLE) {
                int mh = mediaView.getHeight();
                int sy = videoLayout.getScrollY();
                float my = mediaView.getY();
                tempDown = dy > 0;
                if (tempDown) {
//                    if(sy <= mh + my+8) {
                    videoLayout.scrollBy(dx, dy);
//                        JLog.e("pull up mediaview: x:"+mediaView.getX()+"  y:"+mediaView.getY()+" h:"+mediaView.getHeight()
//                                + "  lay scroll y:"+videoLayout.getScrollY());

//                        if (videoLayout.getScrollY() - mediaView.getY() >= mh / 2) {
//                            stopVideoView();
//                            if (isAutoPlayNext) {
//                                if (stateTemp != RecyclerView.SCROLL_STATE_SETTLING && Math.abs(dy) < 20) {
//                                    if (autoPlay != null) {
//                                        if (tempDown) {
//                                            autoPlay.autoNext(parentView, true);
//                                        } else {
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }

                } else {
//                    if (sy>=my-videoLayout.getHeight()-8) {
                    videoLayout.scrollBy(dx, dy);
//                        JLog.e("pull down mediaview: x:"+mediaView.getX()+"  y:"+mediaView.getY()+" h:"+mediaView.getHeight()
//                                + "  lay scroll y:"+videoLayout.getScrollY());
//                    }
                }
            }
        }
    };

    private View.OnClickListener defPlayerMenuClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            playerMenuClick.onClick(view);
        }
    };

    private View.OnClickListener defPlayerNextClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (playerNextClick != null) {
                playerNextClick.onClick(view);
            }
        }
    };

//    private WoPlayerView.OnNetPrompt defNetPrompt = new WoPlayerView.OnNetPrompt() {
//        @Override
//        public boolean onNetPrompt() {
//            return netPrompt != null && netPrompt.onNetPrompt();
//        }
//    };

//    private WoPlayerView.IPanlShowingListener defPanlListener = new WoPlayerView.IPanlShowingListener() {
//        @Override
//        public void onPanlShow() {
//            if (panlShowingListener != null) {
//                panlShowingListener.onPanlShow();
//            }
//        }
//
//        @Override
//        public void onPanlHide() {
//            if (panlShowingListener != null) {
//                panlShowingListener.onPanlHide();
//            }
//        }
//    };

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, String path) {
        this(context, parentView, videoLayout, path, true);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout
            , int otherHeight, List<? extends IPlayClarity> list) {
        this(context, parentView, videoLayout, otherHeight, list, true);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout
            , int otherHeight, List<? extends IPlayClarity> list, boolean playNow) {
        this(context, parentView, videoLayout, otherHeight, "", false, false);
        playerView.setPlaySource(list);
        if (playNow) {
            playerView.setAutoPlay(true).startPlay();
        }
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, int otherHeight) {
        this.context = context;
//        this.isBackValued = isBackValued;
//        speedSdkHelper = new SpeedSdkHelper();
        handler = new Handler(Looper.getMainLooper());
        this.otherHeight = otherHeight;
        if (context instanceof Activity) {
            activity = (Activity) context;
        }
        this.isTop = isTop;
        this.powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        String powerTag = this.getClass().getName();
        if ((context instanceof Activity)) {
            powerTag = context.getClass().getName();
        }
//        this.wakeLock=powerManager.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,powerTag);
        this.wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, powerTag);
        this.parentView = parentView;
        this.videoLayout = videoLayout;
        this.statusHeight = getStatusHeight();
//        init(path, isPlayNow);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, int otherHeight, String path) {
        this(context, parentView, videoLayout, otherHeight, path, true, false);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, String path, boolean isPlayNow) {
        this(context, parentView, videoLayout, 0, path, isPlayNow, false);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, String path, boolean isPlayNow, boolean isTop) {
        this(context, parentView, videoLayout, 0, path, isPlayNow, isTop);
    }

    public FloatVideoUtils(Context context, View parentView, AbsoluteLayout videoLayout, int otherHeight, String path, boolean isPlayNow,
                           boolean isTop) {
        this.context = context;
//        this.isBackValued = isBackValued;
//        speedSdkHelper = new SpeedSdkHelper();
        handler = new Handler(Looper.getMainLooper());
        this.otherHeight = otherHeight;
        if (context instanceof Activity) {
            activity = (Activity) context;
        }
        this.isTop = isTop;
        this.powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        String powerTag = this.getClass().getName();
        if ((context instanceof Activity)) {
            powerTag = context.getClass().getName();
        }
//        this.wakeLock=powerManager.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,powerTag);
        this.wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, powerTag);
        this.parentView = parentView;
        this.videoLayout = videoLayout;
        this.statusHeight = getStatusHeight();
        init(path, isPlayNow);
    }

    public void setCurrentPostion(long currentPostion) {
        this.currentPostion = currentPostion;
    }

    private void init(List<? extends IPlayClarity> list, int pos, boolean playNow) {
        if (isPortrait) {
            flParam = new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 0);
            flParam.width = parentView.getWidth();
            flParam.height = parentView.getHeight();
            JLog.e("isTOp=" + isTop);
            if (!isTop) {
                int[] location = new int[2];
                parentView.getLocationInWindow(location);

                flParam.x = location[0];
//                flParam.y = location[1] ;
                flParam.y = location[1] - statusHeight - otherHeight;
            }
        } else {
            flParam = new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, 0, 0);
        }
        if (pos >= list.size()) {
            pos = 0;
        }
        if (mediaView == null) {
///
            initFloatView();

            if (mediaView.getVisibility() == View.GONE) {
                mediaView.setVisibility(View.VISIBLE);
            }
//            initVideo(mediaView, path, currentPostion);

            if (playNow) {
                playerView.setPlaySource(list).switchStream(pos).startPlay();
            } else {
//                playerView.hideBottonBar(true);
//                playerView.hideCenterPlayer(false);
                playerView.setAutoPlay(false);
//                playerView.hideHideTopBar(false);
                playerView.switchStream(pos);
            }

        } else {

            videoLayout.updateViewLayout(mediaView, flParam);
//            mVideoView.stopPlayback();//
//            mVideoView.setVideoURI(Uri.parse(path));//
//                    logE("NewsDetailActivity","initVideoView has set videouri ->\n"+path);
//            mVideoView.start();//
//                    logE("NewsDetailActivity","initVideoView has call start");
            if (mediaView.getVisibility() == View.GONE) {
                mediaView.setVisibility(View.VISIBLE);
            }
            if (playNow) {
                playerView.setPlaySource(list).switchStream(pos).startPlay();
            } else {
                playerView.switchStream(pos);
            }
        }
    }

    private void init(String path, boolean playNow) {
        flParam = new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 0);
        flParam.width = parentView.getWidth();
        flParam.height = parentView.getHeight();
        if (!isTop) {
            int[] location = new int[2];
            parentView.getLocationInWindow(location);

            flParam.x = location[0];
//                flParam.y = location[1] ;
            flParam.y = location[1] - statusHeight - otherHeight;
        }
        if (mediaView == null) {
///
            initFloatView();

            if (mediaView.getVisibility() == View.GONE) {
                mediaView.setVisibility(View.VISIBLE);
            }
//            initVideo(mediaView, path, currentPostion);

            if (playNow) {
                playerView.setPlaySource(path).setAutoPlay(true).startPlay();
            } else {
//                playerView.hideBottonBar(true);
//                playerView.hideCenterPlayer(false);
                playerView.setAutoPlay(false);
//                playerView.hideHideTopBar(false);
            }

        } else {

            videoLayout.updateViewLayout(mediaView, flParam);
//            mVideoView.stopPlayback();//
//            mVideoView.setVideoURI(Uri.parse(path));//
//                    logE("NewsDetailActivity","initVideoView has set videouri ->\n"+path);
//            mVideoView.start();//
//                    logE("NewsDetailActivity","initVideoView has call start");
            if (mediaView.getVisibility() == View.GONE) {
                mediaView.setVisibility(View.VISIBLE);
            }
            if (playNow) {
                playerView.setPlaySource(path).setAutoPlay(true).startPlay();
            } else {
            }
        }
//                myData.setmParentView(parentView);
//                myData.setVideoInfo(path);
//                myData.setmMediaView(mediaView);
    }

    private void initFloatView() {
        if (mediaView == null) {
//            mediaView = LayoutInflater.from(context).inflate(R.layout.activity_news_detail_video, null);
            mediaView = LayoutInflater.from(context).inflate(R.layout.gplayer_base, null);
            JLog.e("" + (mediaView.getId() == R.id.gplayer_lay_base));
            if (isBackValued) {
                if (backView == null) {
                    backView = new View(context);
                    backView.setBackgroundColor(backViewColor == 0 ? Color.WHITE : backViewColor);
                }
                AbsoluteLayout.LayoutParams alp = new AbsoluteLayout.LayoutParams(flParam);
//                JLog.e("back x:" + alp.x + " y:" + alp.y + " w:" + alp.width);
                alp.x = 0;
                alp.y = 0;
                videoLayout.addView(backView, alp);
            }
            videoLayout.addView(mediaView, flParam);
            playerView = new GPlayerView((Activity) context, mediaView, constructorCallback)
                    .setOnStatusChanged(this).setLive(isLiving).setAutoPlay(true).forbidTouch(false).setSeekCompleteListener
                            (seekCompleteListener).setOnInfoListener(this);
//                    .setScaleType(PlayStateParams.f16_9).setOnNetPrompt(defNetPrompt)
//                    .setForbidHideControlPanl(false).Demand()
//                    .setFullScreenListener(playerViewFullListerner).setPanlShowingListener(defPanlListener)
//                    .setPlayingTimeListener(playingTimeListener);
//            if (playerMenuClick != null) {
//                playerView.setMenuClickListener(defPlayerMenuClick);
//            }
//            setTopMode(topMode);
            if (shouldSetClaryty) {
                setClarities(claritiesTemp);
                shouldSetClaryty = false;
            }
            mediaView.setVisibility(View.GONE);
        } else {
            if (parentView != null) {
                flParam.width = parentView.getWidth();
                flParam.height = parentView.getHeight();

                int[] location = new int[2];
                parentView.getLocationInWindow(location);
                flParam.x = location[0];
//                flParam.y = location[1] ;
                flParam.y = location[1] - statusHeight - otherHeight;
//				mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_FIT_PARENT, 0);
                videoLayout.updateViewLayout(mediaView, flParam);
            }
        }

        if (mediaView != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (context.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                        if (parentView != null) {
                            parentHeight = parentView.getHeight();
                            parentWidth = parentView.getWidth();
                            int[] location = new int[2];
                            parentView.getLocationInWindow(location);
                            parentX = location[0];
                            parentY = location[1];
//                        Log.e("parentView onChange before", "parentX:" + parentX + " parentY:" + parentY);
                        }
                    }
                }
            }, 200);
        }
    }

    public FloatVideoUtils setConstructorCallback(IGPlayerConstructorCallback constructorCallback) {
        this.constructorCallback = constructorCallback;
        return this;
    }

    public FloatVideoUtils setLiving(boolean living) {
        isLiving = living;
        if (playerView != null) {
            playerView.setLive(isLiving);
        }
        return this;
    }

    public void play(View parentView, String url) {
        JLog.e("url:" + url);
        if (parentView == null || TextUtils.isEmpty(url)) {
            return;
        }
//        if(isPlaying()){
        stopVideoView();
//        }
        this.parentView = parentView;
        videoLayout.scrollTo(0, 0);

        init(url, true);
    }

    public void play(View parentView, List<? extends IPlayClarity> list, int pos) {
        if (parentView == null || list == null || list.size() == 0) {
            return;
        }
        stopVideoView();
        this.parentView = parentView;
        videoLayout.scrollTo(0, 0);

        init(list, pos, true);

    }

//    public FloatVideoUtils setLogin(boolean login) {
//        isLogin = login;
//        return this;
//    }

    public void scrollBy(int dx, int dy) {
        videoLayout.scrollBy(dx, dy);
    }

    public void scrollTo(int dx, int dy) {
        videoLayout.scrollTo(dx, dy);
    }

    public boolean isShowing() {
        return mediaView != null && mediaView.getVisibility() == View.VISIBLE;
    }

//    public boolean hasPrepared() {
//        return playerView != null && playerView.hasPrepared();
//    }

    public boolean isShowControlPanl() {
        return playerView != null && playerView.isShowControlPanl();
    }

    public void setClarities(List<IPlayClarity> clarities) {
        JLog.e("clarities::" + clarities);
        claritiesTemp = clarities;
        if (playerView == null) {
            shouldSetClaryty = true;
        } else {
            if (clarities != null && clarities.size() > 0) {
//                List<VideoijkBean> list = new ArrayList<>();
//                for (int i = 0; i < clarities.size(); i++) {
//                    WoClarity wc = clarities.get(i);
//                    if (wc != null) {
//                        VideoijkBean vb = new VideoijkBean();
//                        vb.setStream(wc.getName());
//                        vb.setUrl(wc.getUrl());
//                        list.add(vb);
//                    }
//                }
                playerView.setPlaySource(clarities);
            }
        }
    }

    public void setClarities(List<IPlayClarity> clarities, int defPos) {
        JLog.e("clarities::" + clarities);
        claritiesTemp = clarities;
        if (playerView == null) {
            shouldSetClaryty = true;
        } else {
            if (clarities != null && clarities.size() > 0) {
                playerView.setPlaySource(clarities, defPos);
            }
        }
    }

    public void startPlay() {
        if (playerView == null) {
            JLog.e("Can't start play because player view is null");
            return;
        }
        if (mediaView.getVisibility() == View.GONE) {
            mediaView.setVisibility(View.VISIBLE);
        }
        playerView.setAutoPlay(isPlayerAutoPlay);
        playerView.startPlay();
    }

    public void startPlay(Integer position) {
        JLog.e("ondemand position=" + position);
        if (playerView == null) {
            JLog.e("Can't start play because player view is null");
            return;
        }
        if (mediaView.getVisibility() == View.GONE) {
            mediaView.setVisibility(View.VISIBLE);
        }
        playerView.setAutoPlay(isPlayerAutoPlay);
        if (position != null && position > 0) {
            JLog.e("ondemand will seek to " + position);
            playerView.seekTo(position);
        }
        playerView.startPlay();
    }

//    public FloatVideoUtils setClarityChangedListener(IClarityChanged clarityChangedListener) {
//        if (playerView != null) {
//            playerView.setClarityChanged(clarityChangedListener);
//        }
//        return this;
//    }

    public boolean isPlaying() {
//        return playerView != null && playerView.getStatus() == PlayStateParams.STATE_PLAYING;
        return playerView != null && playerView.isPlaying();
    }

    public boolean isStoped() {
        return playerView == null || playerView.getStatus() == PlayStateParams.STATE_IDLE;
    }

    public List<IPlayClarity> getClaritiesTemp() {
        return claritiesTemp;
    }

    public FloatVideoUtils forbidTouch(boolean isForbid) {
        if (playerView != null) {
            playerView.forbidTouch(isForbid);
        }
        return this;
    }

    public FloatVideoUtils operatorPanl() {
        if (playerView != null) {
            playerView.operatorPanl();
        }
        return this;
    }

//    public FloatVideoUtils hideListLay(boolean isHide) {
//        if (playerView != null) {
//            playerView.hideListLay(isHide);
//        }
//        return this;
//    }

//    public FloatVideoUtils setTopMode(int topMode) {
//        this.topMode = topMode;
//        if (playerView != null) {
//            if (topMode == TOPMODE_LIVING) {
//                playerView.Living();
//            } else if (topMode == TOPMODE_DEMAND) {
//                playerView.Demand();
//            } else {
//                playerView.defaultTopAdapter();
//            }
//        }
//        return this;
//    }

//    public FloatViedioUtils setLoginViewVisible(int visible) {
//        if (playerView != null) {
//            playerView.setLoginViewVisible(visible);
//        }
//        return this;
//    }

    public FloatVideoUtils setScrolledY(int scrolledY) {
        this.scrolledY = scrolledY;
        return this;
    }

    public FloatVideoUtils setShowFull(boolean showFull) {
        isShowFull = showFull;
        return this;
    }

    public FloatVideoUtils setBackValued(boolean backValued) {
        isBackValued = backValued;
        return this;
    }

    public FloatVideoUtils setBackViewColor(int backViewColor) {
        this.backViewColor = backViewColor;
        return this;
    }

    public GPlayerView getPlayerView() {
        return playerView;
    }

    public boolean onBackPress() {
        if (playerView != null) {
            return playerView.onBackPressed();
        }
        return false;
    }

//    public void showThumbnail(OnShowThumbnailListener showThumbnailListener) {
//        if (showThumbnailListener != null) {
//            playerView.showThumbnail(showThumbnailListener);
//        }
//    }

    public RecyclerView.OnScrollListener getRecyclerScrollListener() {
        return recyclerScrollListener;
    }

//    private View.OnClickListener playerViewFullListerner = new View.OnClickListener() {
//        @Override
//        public void onClick(View view) {
//            if (fullScreenClick == null || !fullScreenClick.onFullScreenClick()) {
//                playerChangeFull();
//            }
//        }
//    };

    private void playerChangeFull() {
        currentPostion = playerView.getCurrentPosition();
//            TextView tv = (TextView) view;
//            currentPath = path;
        if (context.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
//                    isPortrait = false;
            if (parentView != null) {
                parentHeight = parentView.getHeight();
                parentWidth = parentView.getWidth();
                int[] location = new int[2];
                parentView.getLocationInWindow(location);
                parentX = location[0];
                parentY = location[1];
//                        Log.e("parentView onChange before", "parentX:" + parentX + " parentY:" + parentY);
            }
//                    tv.setBackgroundResource(R.drawable.player_media_fullscreen_shrink);
            // 强制重力感应横屏
            if (context instanceof Activity) {
                ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }

        } else {
            quitFullScreen();
//                    tv.setBackgroundResource(R.drawable.player_media_fullscreen_stretch);
//                    isPortrait = true;

            if (tempParam != null) {
                flParam = tempParam;
            }
//					mVideoView.getHolder().setFixedSize(flParam.width, flParam.height);
//                mVideoView.setVideoSize(flParam.width,flParam.height);

//					mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_FIT_PARENT, 0);
            videoLayout.updateViewLayout(mediaView, flParam);
            // 强制竖屏
            if (context instanceof Activity) {
                ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }

        }
    }

    public void onChangeToPortrait() {
        isPortrait = true;
        if (playerView != null) {
            playerView.setPortrait(true);
        }
        quitFullScreen();
        if (parentView != null) {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {

                    if (parentView != null) {
                        if (!isTop) {
                            int[] location = new int[2];
                            parentView.getLocationInWindow(location);

                            flParam.x = location[0];
                            flParam.y = location[1] - statusHeight - otherHeight;
                        }
                        flParam.width = parentWidth;
                        flParam.height = parentHeight;
                        if (flParam.y < 0 && isShowFull) {
                            flParam.y = 0;
                        }
                        videoLayout.setClickable(false);
//                        videoLayout.scrollTo(scrollTemp.dx,scrollTemp.dy);

                    }
                    if (playerView != null) {
                        videoLayout.updateViewLayout(mediaView, flParam);
                        playerView.onPortraitControll();
//                        playerView.onChangedToPortrait();
                    }

                }
            }, 100);
        }
    }

    public void refreshVideoLocation() {//刷新播放器位置
        if (parentView != null) {
            int[] location = new int[2];
            parentView.getLocationInWindow(location);
            if (parentWidth <= 0) {
                parentWidth = parentView.getWidth();
            }
            if (parentHeight <= 0) {
                parentHeight = parentView.getHeight();
            }
            flParam.width = parentWidth;
            flParam.height = parentHeight;

            flParam.x = location[0];
            flParam.y = location[1] - statusHeight - otherHeight;
            videoLayout.setClickable(false);
//                        videoLayout.scrollTo(scrollTemp.dx,scrollTemp.dy);

        }
        if (playerView != null) {
            videoLayout.scrollTo(0, 0);
            JLog.e("will update view layout x=" + flParam.x + "  y=" + flParam.y);
            videoLayout.updateViewLayout(mediaView, flParam);
        }
    }

//    public void onConfigurationChangedEnd(Configuration newConfig) {
//        if (playerView != null) {
//            playerView.toggleProcessDurationOrientation(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
//        }
//    }

    public void onChangeToPortraitLandscape() {
        isPortrait = false;
        if (playerView != null) {
            playerView.setPortrait(false);
        }
        if (activity != null) {
            activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        videoLayout.setClickable(true);
        if (parentView != null) {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    flParam.width = videoLayout.getWidth();
                    flParam.height = videoLayout.getHeight();
                    flParam.x = 0;
                    flParam.y = 0;
                    if (playerView != null) {
                        videoLayout.updateViewLayout(mediaView, flParam);
                    }
                    scrollTemp.temp();
                    videoLayout.scrollTo(0, 0);
                    if (playerView != null) {
                        playerView.onLandscapeControll();
                    }

                }
            }, 200);
        }
    }

    public void onPause() {
        if (playerView != null) {
            playerView.onPause();
        }
//        speedSdkHelper.stop(context);
    }

    public void onDestory() {
        seekCompleteListener = null;
        onInfoListener = null;
        onPlayingListener = null;
        seekCompleteListener = null;
        playerMenuClick = null;
        playerNextClick = null;
        if (playerView != null) {
            playerView.onDestroy();
        }
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
        context = null;
        activity = null;
        playerView = null;
        System.gc();
    }

    public void onResume() {
        if (playerView != null) {
            playerView.onResume();
//            if (!playerView.getPlayBtnEnable()) {
//                playerView.pausePlay();
//            }
        }
    }

    /**
     * 动态取消全屏
     */
    private void quitFullScreen() {
        if (context instanceof Activity) {
            Activity a = (Activity) context;
            final WindowManager.LayoutParams attrs = a.getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            a.getWindow().setAttributes(attrs);
            a.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    private void videoPlay() {
        ivDefaultPic.setVisibility(View.GONE);
//        logE("NewsDetailActivity","videoPlay has call start");
//        circlePb.setVisibility(View.GONE);
    }

    public void pausePlay() {
        if (playerView != null) {
            playerView.pausePlay();
        }
//        speedSdkHelper.stop(context);
    }

    public void stopVideoView() {
        if (mediaView != null) {
            mediaView.setVisibility(View.GONE);
        }
        if (playerView != null) {
            playerView.stopPlay();
            if (mediaView != null && mediaView.getVisibility() == View.GONE) {
                playerView.callPlayerHide();
            }
        }
        if (onPlayingListener != null) {
            onPlayingListener.onChangedToStop();
        }
        if (wakeLock.isHeld()) {
            wakeLock.release();
        }
        if (videoLayout != null && videoLayout.getScrollX() != 0) {
            videoLayout.scrollTo(0, 0);
        }
//        speedSdkHelper.stop(context);
    }

    private void showVideView() {
        if (isStop) {
        }
    }

    /**
     * 设置播放信息监听回调
     */
    public FloatVideoUtils setOnInfoListener(IMediaPlayer.OnInfoListener onInfoListener) {
        this.onInfoListener = onInfoListener;
        return this;
    }

//    public FloatVideoUtils setPlayingTimeListener(WoPlayerView.IPlayingTimeListener playingTimeListener) {
//        this.playingTimeListener = playingTimeListener;
//        if (playerView != null) {
//            playerView.setPlayingTimeListener(playingTimeListener);
//        }
//        return this;
//    }

//    public FloatVideoUtils setNetPrompt(WoPlayerView.OnNetPrompt netPrompt) {
//        this.netPrompt = netPrompt;
//        return this;
//    }

//    public FloatViedioUtils setFullScreenClick(WoPlayerView.IFullScreenClick fullScreenClick) {
//        this.fullScreenClick = fullScreenClick;
//        return this;
//    }

//    public FloatViedioUtils setPanlShowingListener(WoPlayerView.IPanlShowingListener panlShowingListener) {
//        this.panlShowingListener = panlShowingListener;
//        return this;
//    }

    public FloatVideoUtils setOnPlayingListener(OnPlayingListener onPlayingListener) {
        this.onPlayingListener = onPlayingListener;
        return this;
    }

    public FloatVideoUtils setSeekCompleteListener(IMediaPlayer.OnSeekCompleteListener seekCompleteListener) {
        this.seekCompleteListener = seekCompleteListener;
        if (playerView != null) {
            playerView.setSeekCompleteListener(seekCompleteListener);
        }
        return this;
    }

    public FloatVideoUtils setOnStatusChanged(OnStatusChanged onStatusChanged) {
        this.onStatusChanged = onStatusChanged;
        return this;
    }

//    public FloatVideoUtils setPlayerMenuClick(View.OnClickListener playerMenuClick) {
//        if (playerMenuClick == null) {
//            if (playerView != null) {
//                playerView.setMenuClickListener(null);
//            }
//        } else {
//            if (playerView != null) {
//                playerView.setMenuClickListener(defPlayerMenuClick);
//            }
//        }
//        this.playerMenuClick = playerMenuClick;
//        return this;
//    }

//    public FloatViedioUtils setPlayerNextClick(View.OnClickListener playerNextClick) {
//        if (playerNextClick == null) {
//            if (playerView != null) {
//                playerView.setNextClickListener(null);
//            }
//        } else {
//            if (playerView != null) {
//                playerView.setNextClickListener(defPlayerNextClick);
//            }
//        }
//        this.playerNextClick = playerNextClick;
//        return this;
//    }

    public FloatVideoUtils setOtherHeight(int otherHeight) {
        this.otherHeight = otherHeight;
        return this;
    }

    public FloatVideoUtils setAutoPlayNext(boolean autoPlayNext) {
        isAutoPlayNext = autoPlayNext;
        return this;
    }

    public FloatVideoUtils setIAutoPlay(IAutoPlayAction autoPlay) {
        this.autoPlay = autoPlay;
        isAutoPlayNext = autoPlay != null;
        return this;
    }

    public FloatVideoUtils setPlayerAutoPlay(boolean playerAutoPlay) {
//        boolean b=this.isPlayerAutoPlay!=playerAutoPlay;
        isPlayerAutoPlay = playerAutoPlay;
        if (playerView != null) {
            playerView.setAutoPlay(isPlayerAutoPlay);
        }
        return this;
    }

//    public WoPlayerView.IPlayingTimeListener getPlayingTimeListener() {
//        return playingTimeListener;
//    }

//    public boolean isUnPlayingByEnable() {
//        return playerView != null && !playerView.getPlayBtnEnable();
//    }

    /**
     * 获得状态栏的高度
     *
     * @param
     * @return
     */
    public int getStatusHeight() {

        int statusHeight = -1;
        try {
            Class clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = activity.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("getStatusHeight", "getStatusHeight:" + statusHeight);
        return statusHeight;
    }

    public View getParentView() {
        return parentView;
    }

    public void setParentView(View parentView) {
        this.parentView = parentView;
    }

//    public CustomMediaController getMediaController() {
//        return mediaController;
//    }

//    public int getTopHorHeight() {
//        int re = 0;
//        if (playerView != null) {
//            re = playerView.getTopHorHeight();
//        }
//        return re;
//    }

//    public void setMediaController(CustomMediaController mediaController) {
//        this.mediaController = mediaController;
//    }

    public boolean isAboutStatusHeiht() {
        return isAboutStatusHeiht;
    }

    public void setAboutStatusHeiht(boolean aboutStatusHeiht) {
        isAboutStatusHeiht = aboutStatusHeiht;
    }

    public View getMediaView() {
        return mediaView;
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int percent) {
//        circlePb.setProgress(percent);
        if (percent > 0 && pb.getVisibility() == View.VISIBLE) {
            pb.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
        JLog.e("what=" + what + "   extra=" + extra + "   status=" + playerView.getStatus());
//        speedSdkHelper.onInfo(context, iMediaPlayer, getPlayerView().getCurrentCalarity(), what);
        if (onInfoListener != null) {
            return onInfoListener.onInfo(iMediaPlayer, what, extra);
        }
        return false;
    }

    @Override
    public void onStatusChanged(int nesStatus) {
        switch (nesStatus) {
            case PlayStateParams.STATE_PLAYING:
//            case PlayStateParams.MEDIA_INFO_BUFFERING_START:
//
                if (onPlayingListener != null) {
                    onPlayingListener.onChangedToPlaying();
                }
                break;
            case PlayStateParams.STATE_PAUSED:
                if (onPlayingListener != null) {
                    onPlayingListener.onChangeToUnPlaying();
                }
                break;
            case PlayStateParams.STATE_ERROR:
            case PlayStateParams.STATE_COMPLETED:
            case PlayStateParams.STATE_IDLE:
//
                if (onPlayingListener != null) {
                    onPlayingListener.onChangeToUnPlaying();
                    onPlayingListener.onChangedToStop();
                }
                break;
        }
        if (onStatusChanged != null) {
            onStatusChanged.onStatusChanged(nesStatus);
        }
    }

    private void wakeScreen() {
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
            JLog.e("wake locked with ");
        } else {
            JLog.e("int state playing wake lock is acquired");
        }
    }

    private void releaseScreen() {
        if (wakeLock.isHeld()) {
            parentView.callOnClick();
//                    wakeLock.release();
//                    wakeLock.release(1);
            try {
//                Object obj = Utils.invokeMethod(wakeLock, "release", 1);
//                        if("Error".equals(obj)){
//                            wakeLock.release();
//                        }
            } catch (Exception e) {
                e.printStackTrace();
                wakeLock.release();
            }
            JLog.e("wake released with ");
        } else {
            JLog.e("int state E P C wake lock is not acquired");
        }
    }

    private class ScrollTemp {
        protected int dx;
        protected int dy;

        protected void temp() {
            if (videoLayout != null) {
                dx = videoLayout.getScrollX();
                dy = videoLayout.getScrollY();
            }
        }
    }

    public boolean isTop() {
        return isTop;
    }

    public void setTop(boolean top) {
        isTop = top;
    }
}
